package team.cdlzz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import team.cdlzz.dao.FileDataMapper;
import team.cdlzz.dao.QuestionMapper;
import team.cdlzz.dao.UserMapper;
import team.cdlzz.model.pojo.FileData;
import team.cdlzz.model.pojo.Question;
import team.cdlzz.model.pojo.User;
import team.cdlzz.model.servicePojo.UploadProperties;
import team.cdlzz.util.IDUtils;
import team.cdlzz.util.UploadUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zw
 * @date 2022-06-26.
 */
@Service
public class UploadService {

    @Autowired
    private UploadProperties uploadProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private FileDataMapper fileDataMapper;

    @Transactional //升级为事务用于回滚
    public String uploadImage(MultipartFile file) throws IOException {
        if(!uploadProperties.getAllowTypes().contains(file.getContentType())){
            throw new IOException("文件上传类型错误！");
        }
        System.out.println(file.getContentType()+ " === "+file.getContentType().equals("application/vnd.ms-excel"));
        String fileName = UploadUtils.generateFileName(file.getOriginalFilename());
        if (file.getContentType().equals("application/vnd.ms-excel")){
            file.transferTo(new File(uploadProperties.getPath_excel()+fileName));//写入文件
            List<Question> workQuestionList = IDUtils.getWorkQuestionList(uploadProperties.getPath_excel() + fileName);
            if (workQuestionList.size()>=3500){
                List list1 = workQuestionList.subList(0,3500);
                List list2 = workQuestionList.subList(3500,workQuestionList.size());
//                System.out.println(list2.get(1).toString());
                int b1 =  questionMapper.insertList(list1);
                int b2 =  questionMapper.insertList(list2);

            }else {
                int b =  questionMapper.insertList(workQuestionList);

            }

        }else {
            file.transferTo(new File(uploadProperties.getPath_img()+fileName));
        }
        System.out.println(uploadProperties.getPath_img()+fileName);
        return fileName;

    }

    public String uploadCourseFile(MultipartFile file, Integer cid, Integer uid) {
        String name = file.getOriginalFilename();
        System.out.println("filename == " + name);
        String fileName = UploadUtils.generateFileName(name); //获取文件名字
        try {
            file.transferTo(new File(uploadProperties.getPath_excel()+fileName));//写入文件
            String time = getNowTime();//获取当前时间
            int fileSize = getFileSize(fileName); //获取文件大小
            FileData fileData = new FileData(null,fileName,cid,uid,time, fileSize,name);
            fileDataMapper.insert(fileData);
        } catch (IOException e) {
            throw new RuntimeException("文件写入错误,出现了IO异常");
        }
        return IDUtils.getPath(fileName,4);
    }
    public String uploadCourse(MultipartFile file) {
        String name = file.getOriginalFilename();
        System.out.println("filename == " + name);
        String fileName = UploadUtils.generateFileName(name); //获取文件名字
        try {
            file.transferTo(new File(uploadProperties.getPath_excel()+fileName));//写入文件
        } catch (IOException e) {
            throw new RuntimeException("文件写入错误,出现了IO异常");
        }
        return fileName;
    }

    public String getNowTime(){
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(date);
    }
    public int getFileSize(String fileName){
        return   (int)new File("D:\\Img\\" + fileName).length();

    }

    public String downLoad(HttpServletResponse response, String filename) throws UnsupportedEncodingException {

        FileData fileData = fileDataMapper.selectByFilename(filename);
        //要下载的文件路径
        File file = new File("D:\\Img\\" + filename);

        String fileName = fileData.getName();
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Length", "" + file.length());
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

                System.out.println("文件下载完成！！");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }


//    public String uploadImage(MultipartFile file, Integer uid) {
//
//    }
    public String uploadImage(MultipartFile file, Integer uid) {
        String name = file.getOriginalFilename();
        System.out.println("filename == " + name);
        String fileName = UploadUtils.generateFileName(name); //获取文件名字
        try {
            file.transferTo(new File(uploadProperties.getPath_excel()+fileName));//写入文件
            User user = new User();
            user.setUid(uid);
            user.setPhoto(fileName);
            int i = userMapper.updateByPrimaryKeySelective(user);
            System.out.println(i);
        } catch (IOException e) {
            throw new RuntimeException("文件写入错误,出现了IO异常");
        }
        return IDUtils.getPath(fileName,4);
    }
}
